package com.theme.passport.controller.theme;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.theme.common.mvc.utils.FileUploadParam;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.constant.ThemeAttchmentTypeEnum;
import com.theme.passport.entity.theme.ThemeAttachmentEntity;
import com.theme.passport.entity.theme.ThemeEntity;
import com.theme.passport.entity.theme.WidgeEntity;
import com.theme.passport.entity.theme.WidgeLayoutEntity;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.ThemeAttachmentService;
import com.theme.passport.service.theme.ThemeService;
import com.theme.passport.service.theme.WidgeLayoutService;
import com.theme.passport.service.theme.WidgeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 壁纸主题表
 *
 * @author live
 * @email 870459550@qq.com
 * @date 2020-11-23 10:57:59
 */
@RestController
@RequestMapping("theme/theme-list")
public class ThemeListController extends AbstractController {
    @Autowired
    private ThemeService themeService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WidgeService widgeService;

    @Autowired
    private WidgeLayoutService widgeLayoutService;

    @Autowired
    private ThemeAttachmentService attachmentService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("theme:theme-list:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = themeService.queryPage(params);
        List<ThemeEntity> list = (List<ThemeEntity>) page.getList();
        list.forEach(theme ->{
            SysUserEntity byId = sysUserService.getById(theme.getUserId());
            theme.setUseNickname(byId.getNickname());
            String label = theme.getLabel();
            if (label != null){
                String[] split = label.split(",");
                theme.setLabels(Arrays.asList(split));
            }
        });
        page.setList(list);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("theme:theme-list:info")
    public R info(@PathVariable("id") Long id){
        ThemeEntity theme = themeService.getById(id);
        SysUserEntity byId = sysUserService.getById(theme.getUserId());
        theme.setUseNickname(byId.getNickname());
        //获取主题详情图图片：
        QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
        fileNameWrapper.and(wrapper -> wrapper
                .eq("type", ThemeAttchmentTypeEnum.THEME.getValue())
                .eq("object_id", id));
        List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
        List<String> images = new ArrayList<>();
        attachmentList.forEach(attachment -> {
            images.add(attachment.getFileUrl());
        });
        theme.setImages(images);
        String label = theme.getLabel();
        if (label != null){
            String[] split = label.split(",");
            theme.setLabels(Arrays.asList(split));
        }
        return R.ok().put("theme", theme);
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("theme:theme-list:delete")
    public R delete(@RequestBody Long[] ids){
        //删除主题操作：
        List<Long> themeIds = Arrays.asList(ids);
        if (themeIds != null && themeIds.size() > 0){
            themeIds.forEach(themeId ->{
                ThemeEntity themeEntity = themeService.getById(themeId);
                String fileName = themeEntity.getFileName(); //轻奢雅黑.zip
                File file = new File(fileName);
                String fileNameTemp = file.getName().substring(0,file.getName().lastIndexOf("."));
                //删除单个文件
                String themeZip = FileUploadParam.THEME_ZIP.getWebUrl() + fileName;
                OSSFactory.build(null).deleteObject(themeZip);

                //删除整个目录
                String theme = FileUploadParam.THEME.getWebUrl() + fileNameTemp;
                OSSFactory.build(null).deleteObjectDir(theme);

                //删除主题组件和组件配置：
                List<WidgeEntity> widgeList = widgeService.queryWidgeList(themeId);
                widgeList.forEach(widge ->{
                    //themeWidgeLayoutService.deleteThemeWidgeLayoutByThemeWidgeId(themeWidge.getId());
                    widgeLayoutService.remove(Wrappers.<WidgeLayoutEntity>query().lambda().eq(WidgeLayoutEntity::getWidgeId, widge.getId()));
                });
                //themeWidgeService.deleteThemeWidgeByThemeId(themeId);
                widgeService.remove(Wrappers.<WidgeEntity>query().lambda().eq(WidgeEntity::getThemeId, themeId));

                //删除主题详情图附件
                QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
                fileNameWrapper.and(wrapper -> wrapper
                        .eq("type", ThemeAttchmentTypeEnum.THEME.getValue())
                        .eq("object_id", themeId));
                List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
                if (attachmentList != null && attachmentList.size() >0 ){
                    attachmentList.forEach( attachment -> {
                        attachmentService.removeById(attachment.getId());
                    });
                }

            });
            themeService.removeByIds(Arrays.asList(ids));
        }
        return R.ok();
    }
}
